<template>
    <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog">
        <el-form :model="uploadScheduleForm" ref="uploadScheduleFormRef" :rules="uploadScheduleRules">
            <el-form-item label="附件" :label-width="formLabelWidth" prop="fileUrl">
                <el-upload ref="upload" class="upload-demo" :limit="1" :on-exceed="handleExceed" :auto-upload="false"
                    :file-list="fileList" :on-change="fileChange" :before-remove="handleRemove"
                    :on-preview="handleFilePreview" :before-upload="beforeUploadHandler">
                    <template #trigger>
                        <el-button type="primary" style="margin-right: 10px">选择文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel()">取消</el-button>
                <el-button type="primary" @click="submitTask()">提交</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "../../utils/httpService";
import { ElMessage, ElForm, ElDatePicker, ElButton } from "element-plus";
import { vxRule } from '../../utils/validator'
export default {
    name: "uploadScheduleForm",
    components: { ElForm, ElMessage, ElDatePicker, ElButton },
    data() {
        return {
            UploadUserFile: [],
            dialogFormVisible: ref(false),
            formLabelWidth: "120px",
            title: "",
            fileList: [],
            extension: ['xls', 'xlsx'],
            templateUrl: "",
            personnelType: "",
            uploadScheduleForm: {
                fileUrl: "",
            },
            // 校验规则
            uploadScheduleRules: {
            },
        };
    },
    methods: {
        fileChange(file, fileList) {
            let fileName = file.name.substring(file.name.lastIndexOf('.') + 1);
            if (this.extension.indexOf(fileName) >= 0) {
                this.fileList = fileList
            } else {
                fileList.splice(-1, 1);
                ElMessage({
                    message: '不支持上传该类型文件',
                    type: 'warning',
                    offset: 400
                })
            }

        },
        handleRemove() {
        },
        handleExceed(files) {
            let file = files[0];
            let fileList = [file];
            this.fileChange(file, fileList);
        },
        beforeUploadHandler(file) {
        },
        submitTask() {
            this.$refs.uploadScheduleFormRef.validate((valid) => {
                if (valid) {
                    let params = new FormData(), num = 0; //创建一个form对象,必须是form对象否则后端接受不到数据
                    this.uploadScheduleForm.fileUrl = "";
                    if (this.fileList.length > 0) {
                        for (let i in this.fileList) {
                            if (this.fileList[i].raw) {
                                num += 1;
                                params.append("file", this.fileList[i].raw);
                            } else {
                                this.uploadScheduleForm.fileUrl = this.uploadScheduleForm.fileUrl + ';' + this.fileList[i].url
                            }
                        };
                        let config = { "Content-Type": "multipart/form-data" }, uploadApiUrl = "";
                        if (this.title == '上传任课安排') {
                            uploadApiUrl = "/pythonApi/scheduleApi/importClassTeachers"
                        } else {
                            uploadApiUrl = "/pythonApi/scheduleApi/importClassSchedule"
                        }
                        httpService(uploadApiUrl, params, "post", config).then((data) => {
                            if (data.code == 200) {
                                ElMessage.success(data.message ? data.message : data.object ? data.object : "上传成功");
                                this.clear();
                                this.fileList = [];
                                if (this.title == '上传任课安排') {
                                    this.$parent.getClassTeacherList()
                                } else {
                                    this.$parent.getClassScheduleList();
                                }
                            } else {
                                ElMessage.error(data.message ? data.message : data.object ? data.object : "上传失败");
                            }
                        });
                    } else {
                        ElMessage({
                            message: "请选择文件",
                            type: 'error'
                        });
                    }
                } else {
                    return false
                }
            })

        },
        closeDialog() {
            this.clear();
        },
        cancel() {
            this.dialogFormVisible = false;
            this.clear();
        },
        handleFilePreview(file) {
            let config = { "responseType": "blob" };
            httpService("/pythonApi/printingSystem/getFileData", { fileUrl: file.url }, 'get', config).then(
                (data) => {
                    let fileName = file.name, link = document.createElement('a'),
                        fileUrl = window.URL.createObjectURL(new Blob([data]));
                    link.style.display = 'none';
                    link.href = fileUrl;
                    link.setAttribute('download', fileName);
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(fileUrl)
                }
            )
        },
        clear() {
            this.dialogFormVisible = false;
            this.fileList = [];
            //清空form
            this.uploadScheduleForm.fileUrl = "";
        },
        getPrintTaskFormById(id) {
            httpService("/pythonApi/printingSystem/getPrintTaskInfo", { taskId: id }, "get").then(
                (data) => {
                    this.uploadScheduleForm = data.data;
                    this.uploadScheduleForm.taskId = id;
                    this.fileList = data.fileList;
                }
            );
        }
    },
};
</script>
<style></style>